package com.rongke.web;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.rongke.commons.JsonResp;
import com.rongke.model.Coupon;
import com.rongke.model.CouponUser;
import com.rongke.model.Muser;
import com.rongke.model.ReleaseUserCouponRequest;
import com.rongke.service.CouponService;
import com.rongke.service.CouponUserService;
import com.rongke.service.MuserService;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * @version : Ver 1.0
 * @CouponUserController
 * @用户和优惠券中间Controller
 */
@CrossOrigin(origins = "*", maxAge = 3600)
@RestController
@RequestMapping(value = "/api/couponUser")
@Transactional
public class CouponUserController {
    private Logger log = Logger.getLogger(this.getClass());
    @Autowired
    private CouponUserService couponUserService;
    @Autowired
    private CouponService couponService;
    @Autowired
    private MuserService muserService;

    /**
     * @param couponUser
     * @return 返回值JsonResp
     * @添加用户和优惠券中间
     */
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public JsonResp addCouponUser(@RequestBody CouponUser couponUser) {
        log.debug("添加用户和优惠券中间");
        couponUserService.insert(couponUser);
        return JsonResp.ok(couponUser);
    }

    /**
     * @param couponUser
     * @return 返回值JsonResp
     * @修改用户和优惠券中间
     */
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public JsonResp updateCouponUser(@RequestBody CouponUser couponUser) {
        log.debug("修改用户和优惠券中间");
        couponUserService.updateById(couponUser);
        return JsonResp.ok(couponUser);
    }

    /**
     * @param id
     * @return 返回值JsonResp
     * @根据id查找用户和优惠券中间
     */
    @RequestMapping(value = "/selectOne", method = RequestMethod.GET)
    public JsonResp selectCouponUser(Long id) {
        log.debug("查找用户和优惠券中间");
        CouponUser couponUser = couponUserService.selectById(id);
        return JsonResp.ok(couponUser);
    }

    /**
     * 查找某用户的优惠券列表
     *
     * @param userId
     * @param thresholdPrice 商品总价（此价格能使用哪几种优惠券）
     * @return
     */
    @RequestMapping(value = "/selectCouponsByUserId", method = RequestMethod.GET)
    public JsonResp selectCouponsByUserId(Long userId, Double thresholdPrice) {
        log.debug("查找某用户的优惠券列表");
        if (null == userId)
            return JsonResp.toFail("参数不能为空");
        EntityWrapper<CouponUser> ew = new EntityWrapper<>();
        //取未过期优惠券
        Calendar curCal = Calendar.getInstance();
        curCal.setTime(new Date());
        curCal.add(Calendar.DATE, -1);
        ew.eq("muser_id", userId);
        ew.ge("validity_time", curCal.getTime());
        //筛选可用状态
        ew.eq("status", 1);
        ew.orderBy("gmt_datetime", false);

        /*** 更改失效优惠券状态*/
        EntityWrapper<CouponUser> ewc=new EntityWrapper<>();
        ewc.eq("muser_id", userId);
        ewc.lt("validity_time", curCal.getTime());
        ewc.eq("status", 1);
        ewc.setSqlSelect("id");
        List<Object> ids=couponUserService.selectObjs(ewc);
        if(!ids.isEmpty()){
            ids.forEach(e->{
                CouponUser cu=new CouponUser((Long)e);
                cu.setStatus(2);
                couponUserService.updateById(cu);
            });
        }
        List<CouponUser> couponUserList = couponUserService.selectList(ew);
        //设置优惠券详情和查找符合价格的优惠券
        couponUserList = convertCouponType(thresholdPrice, couponUserList);
        return JsonResp.ok(couponUserList);
    }

    //筛选合条件的优惠券列表
    public List<CouponUser> convertCouponType(Double thresholdPrice, List<CouponUser> couponUserList) {
        List<CouponUser> couponUsers = new ArrayList<>();
        for (CouponUser couponUser : couponUserList) {
            Coupon cp = couponService.selectById(couponUser.getCouponId());
            if (cp != null) {
                couponUser.setCoupon(cp);
                if (thresholdPrice != null && thresholdPrice != 0) {
                    if (cp.getType()==2) {
                        //筛选价格达到满减要求并不小于优惠券面值
                        if (thresholdPrice >= cp.getDenomination() && thresholdPrice >= cp.getReachAmount()) {
                            couponUsers.add(couponUser);
                        }
                    } else {
                        //无门槛抵扣时价格需大于面值
                        if (thresholdPrice > cp.getDenomination()) {
                            couponUsers.add(couponUser);
                        }
                    }
                } else {
                    couponUsers.add(couponUser);
                }
            }
        }
        return couponUsers;
    }


    /**
     * 给某用户发放分享优惠券
     *
     * @return
     */
    @RequestMapping(value = "/releaseShareUserCoupon", method = RequestMethod.POST)
    public JsonResp releaseShareUserCoupon(@RequestBody ReleaseUserCouponRequest cuRequest) {
        log.debug("给某用户发放分享优惠券");
        Long muserId = cuRequest.getMuserId();
        if (muserId == null) {
            return JsonResp.toFail("用户id不能为空");
        }
        EntityWrapper<Coupon> ew = new EntityWrapper<>(cuRequest.getCoupon());
        List<CouponUser> cus = new ArrayList<>();
        List<Coupon> coupons = new ArrayList<>();
        coupons = couponService.selectList(ew);
        if (coupons.size() == 0) {
            return JsonResp.ok("暂未找到符合条件的优惠券");
        }
        EntityWrapper<CouponUser> ewcu=new EntityWrapper<>();
        //优惠券来源 1 常规 2 注册所得 3 分享邀请他人注册下载所得 4 分享到朋友圈后
        Integer source=1;
        ewcu.eq("muser_id",muserId);
        if(cuRequest.getCoupon().getDiffTag()!=null){
            //分享注册下载
            if(cuRequest.getCoupon().getDiffTag()==3){
                ewcu.eq("source",3);
                source=3;
            }
            //分享到朋友圈
            if(cuRequest.getCoupon().getDiffTag()==4){
                ewcu.eq("source",4);
                source=4;
            }
        }
        int count=couponUserService.selectCount(ewcu);
        if(source==4&&count>0){
            return JsonResp.ok("已返过朋友圈优惠");
        }
        if(count>=10){
            return JsonResp.ok("已返过达十次分享邀请优惠券");
        }
        cus = couponUserService.releaseCouponsForMuser(muserId, coupons,source);
        couponUserService.insertBatch(cus);
        return JsonResp.ok(cus);
    }

    /**
     * 后台给某用户发放分享优惠券
     *
     * @return
     */
    @RequestMapping(value = "/releaseUserCouponAdmin", method = RequestMethod.POST)
    public JsonResp releaseUserCouponAdmin(@RequestBody CouponUser cu) {
        log.debug("给某用户发放优惠券");
        Long muserId = cu.getMuserId();
        if (muserId == null||cu.getCouponId()==null) {
            return JsonResp.toFail("用户id不能为空");
        }
        EntityWrapper<Muser> ew=new EntityWrapper<>();
        ew.setSqlSelect("id");
        Object userId=muserService.selectObj(ew);
        if(null==userId)
            return JsonResp.toFail("找不到该用户，核对后再试");
       Coupon coupon = couponService.selectById(cu.getCouponId());
        if (coupon == null) {
            return JsonResp.ok("暂未找到符合条件的优惠券");
        }
//        EntityWrapper<CouponUser> ewcu=new EntityWrapper<>();
        //优惠券来源 1 常规 2 注册所得 3 分享邀请他人注册下载所得 4 分享到朋友圈后 5 后台发放
        Integer source=1;
        cu.setNum(1);
        cu.setStatus(1);//可用
        //按天数设置
        if(coupon.getValidityDays()!=null){
            Calendar curCal = Calendar.getInstance();
            curCal.setTime(new Date());
            curCal.add(Calendar.DATE,coupon.getValidityDays());
            Date validityTime = curCal.getTime();
            cu.setValidityTime(validityTime);
        }else{
            cu.setValidityTime(coupon.getExpireTime());
        }
        cu.setSource(source);
        cu.setGmtDatetime(new Date());
        couponUserService.insert(cu);
        return JsonResp.ok(cu);
    }

    public static void main(String[] args) {
        int zz=Calendar.getInstance().get(Calendar.MINUTE);
        int zzz=Calendar.getInstance().get(Calendar.HOUR_OF_DAY);
        System.out.println(zz);
        System.out.println(zzz);
    }
}
